import Vue from 'vue';
import Vuex from 'vuex';
import home from './modules/home.js';
import * as types from './types';
import {fetchUser,validateUser } from '@/api/user';
import {Toast} from 'cube-ui';
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user:{},
    hasPermission:false
  },
  mutations: {
    [types.SET_LOGIN](state,payload){
      state.user = payload;
      state.hasPermission = true;
    }
  },
  actions: {
    async [types.SET_LOGIN]({commit},user){
      try{
        let result = await fetchUser(user);
        commit(types.SET_LOGIN,result);
        localStorage.setItem('token',result.token);//保存token
      }catch(e){
        Toast.$create({
          txt:e.data,
          time:500
        }).show()
        return Promise.reject(e);
      }
    },
    async [types.VALIDATE_USER]({commit}){
      try{
        let user =  await validateUser();
        commit(types.SET_LOGIN,user);
      }catch(e){
        return Promise.reject(e);
      }
    }
  },
  modules: {
    home
  },
});
